package com.hieu.sms.persist;

import java.util.Calendar;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hieu.sms.model.Course;
import com.hieu.sms.model.filter.CourseFilter;
import com.hieu.sms.utils.TextUtil;

@Repository
@Transactional
public class CourseDaoImpl extends AbstractHibernateDAOImpl<Course, Long>
		implements CourseDao {

	@Override
	protected Class<Course> getDomainClass() {
		return Course.class;
	}

	@SuppressWarnings("unchecked")
	public List<Course> findByDepId(String depId) {
		Query query = getSession().getNamedQuery("Course.findByDepId")
				.setString("depId", depId);
		return query.list();
	}

	public List<Course> search(CourseFilter courseFilter) {
		return list(courseFilter);
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public List<Course> list(CourseFilter filter, int startIndex, int pageSize) {
		DetachedCriteria criteria = buildCriteria(filter);

		return (List<Course>) getHibernateTemplate().findByCriteria(criteria,
				startIndex, pageSize);
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public List<Course> list(CourseFilter filter) {
		return list(filter, -1, 300);
	}

	private DetachedCriteria buildCriteria(CourseFilter courseFilter) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Course.class,
				"course");
		if (courseFilter.getDepId() != null) {
			criteria.add(Property.forName("depId").eq(
					courseFilter.getDepId().trim()));
		}
		if (TextUtil.isNotEmpty(courseFilter.getCourseId())) {
			criteria.add(Property.forName("courseId").eq(
					courseFilter.getCourseId().trim()));
		}
		return criteria;

	}

}
